package com.sd.repay.service.impl;

import com.sd.repay.common.Constants;
import com.sd.repay.dao.BaseDao;
import com.sd.repay.pojo.RepayPlan;
import com.sd.repay.pojo.RepayPlanDetail;
import com.sd.repay.pojo.WithdrawOrder;
import com.sd.repay.service.CardManageService;
import com.sd.repay.service.RepayPlanDetailService;
import com.sd.repay.service.RepayPlanService;
import com.sd.repay.service.WithdrawNotifyBaseService;
import com.sd.repay.utils.JsonUtil;
import com.sd.repay.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author sd
 * @Description: 统一出账结果还款类型订单通知Service实现
 * @date 2017年10月25日
 */
@Service
public class RepayWithdrawServiceImpl implements WithdrawNotifyBaseService {

    private static Logger log = LoggerFactory.getLogger(RepayWithdrawServiceImpl.class);

    @Autowired
    private BaseDao baseDao;
    @Autowired
    private RepayPlanDetailService planDetailService;
    @Autowired
    private RepayPlanService planService;
    @Autowired
    private CardManageService cardManageService;


    /**
     * 还款类型统一出账订单业务通知
     *
     * @param withdrawOrder
     * @return
     * @throws Exception
     */
    @Override
    public String reciveWithdrawNotify(WithdrawOrder withdrawOrder) throws Exception {

        String planNo = withdrawOrder.getServiceOrderNo();
        String notifyStatus = withdrawOrder.getStatus();
        String resultMsg = withdrawOrder.getResultMsg();

        log.info("还款类型统一出账订单业务通知处理参数planNo：" + planNo + "，notifyStatus：" + notifyStatus + "，resultMsg：" + resultMsg);
        if (StringUtil.isBlank(planNo, notifyStatus)) {
            return "FAIL";
        }

        RepayPlanDetail planDetail = planDetailService.getDetailByPlanNo(planNo);
        log.info("计划明细编号：" + planNo + "对应的计划明细：" + JsonUtil.objectToJson(planDetail));
        if (null == planDetail) {
            return "FAIL";
        }
        String batchNo = planDetail.getBatchNo();
        int planIndex = planDetail.getPlanIndex();

        RepayPlan repayPlan = planService.getRepayPlanByBatchNo(batchNo);
        log.info("计划批次号：" + batchNo + "对应的还款计划：" + JsonUtil.objectToJson(repayPlan));
        if (null == repayPlan) {
            return "FAIL";
        }
        String planStatus = repayPlan.getStatus();
        String expectStatus = repayPlan.getExpectStatus();

        //根据卡片编号获取卡片对象
        Map<String, Object> cardInfo = cardManageService.getCardManageByCardNo(planDetail.getCardNo());
        if (cardInfo == null || cardInfo.isEmpty()) {
            log.info("计划明细编号：" + planNo + "对应卡片信息不存在");
            return "FAIL";
        }
        String accountNo = StringUtil.filterNull(cardInfo.get("account_no"));

        int count;
        //如果为成功
        if (Constants.WITHDRAW_STATUS_SUCCESS.equals(notifyStatus)) {

            resultMsg = StringUtils.isBlank(resultMsg) ? "支付成功" : resultMsg;

            count = planDetailService.updateDetailStatus(planNo, Constants.PLAN_DETAIL_STATUS_SUCCESS, null, "代付订单回调：" + resultMsg);
            log.info("订单回调更改计划明细编号：" + planNo + "状态为" + Constants.PLAN_DETAIL_STATUS_SUCCESS + "影响的行数为" + count);
            if (count > 0) {
                //判断是否是最后一笔，如果是最后一笔，就标识这个还款计划已完成
                boolean isLast = planDetailService.isLastIndexDetail(batchNo, planIndex);
                if (isLast) {
                    log.info("计划明细编号：" + planNo + "是最后一笔还款明细，且执行成功，故修改计划状态为成功");
                    count = planService.updateRepayPlanStatus(batchNo, Constants.PLAN_STATUS_SUCCESS, Constants.PLAN_STATUS_IN_EXECUTE, "还款完成");
                    log.info("更改还款批次号：" + batchNo + "为还款完成状态影响的行数" + count);

                } else if (Constants.PLAN_EXPECT_STATUS_STOP.equals(expectStatus)) {
                    //如果不是最后一笔，判断此计划是已预处理，如果是，则直接改为终止状态
                    log.info("批次号：" + batchNo + "已预处理，故直接改其批次状态为终止状态");
                    count = planService.updateRepayPlanStatus(batchNo, Constants.PLAN_STATUS_STOP, Constants.PLAN_STATUS_IN_EXECUTE, "用户终止");
                    log.info("更改还款批次号：" + batchNo + "为终止状态影响的行数" + count);
                }
            }

        } else if (Constants.WITHDRAW_STATUS_FAIL.equals(notifyStatus)) {
            count = planDetailService.updateDetailStatus(planNo, Constants.PLAN_DETAIL_STATUS_FAIL, null, "代付订单回调：" + resultMsg);
            log.info("订单回调更改计划明细编号：" + planNo + "状态为" + Constants.PLAN_DETAIL_STATUS_FAIL + "影响的行数为" + count);

            planDetail = planDetailService.getDetailByPlanNo(planNo);
            int planCount = planDetail.getPlanCount();

            if (Constants.PLAN_MAX_EXECUTE_COUNT <= planCount) {

                log.info("计划还款明细编号：" + planNo + "执行次数已经达到" + planCount + "次，且操作次数已到" + Constants.PLAN_MAX_EXECUTE_COUNT + "" +
                        "次，故将其对应批次号：" + batchNo + "状态改为挂起");
                count = planService.updateRepayPlanStatus(batchNo, Constants.PLAN_STATUS_HANG, Constants.PLAN_STATUS_IN_EXECUTE, "计划挂起");
                log.info("更改计划批次号：" + batchNo + "为挂起状态影响的行数" + count);
            }
        }
        return "SUCCESS";
    }
}